package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.LoginFormDTO;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.User;
import com.hmdp.mapper.UserMapper;
import com.hmdp.service.IUserService;
import com.hmdp.utils.*;
import io.lettuce.core.BitFieldArgs;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.data.redis.connection.BitFieldSubCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.LOGIN_CODE_KEY;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {


    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    /**
     * 发送短信验证码并保存验证码
     * @param phone
     * @param session
     * @return
     */
    @Override
    public Result sendCode(String phone, HttpSession session) {
        //1.校验手机号
        if (RegexUtils.isPhoneInvalid(phone)) {
            //2.如果不符合,返回错误信息
            return Result.fail("手机号格式错误");
        }

        //3.如果符合.生成验证码
        //使用hutool包中的API生成6位的随机数
        String code = RandomUtil.randomNumbers(6);
/*

        //4.1.保存验证码保存到Redis
        stringRedisTemplate.opsForValue().set(LOGIN_CODE_KEY+phone,code,RedisConstants.LOGIN_CODE_TTL, TimeUnit.MINUTES);
        //4.2.保存手机号保存到Redis
        stringRedisTemplate.opsForValue().set(RedisConstants.LOGIN_PHONE_KEY+phone,phone,RedisConstants.LOGIN_CODE_TTL, TimeUnit.MINUTES);

*/


        // 获取map的键值对集合
        Map<String, String> data = new HashMap<>();
        data.put(RedisConstants.LOGIN_PHONE_KEY, phone);
        data.put(LOGIN_CODE_KEY, code);

        // 使用opsForHash的putAll方法将Map存入Redis的Hash中
        stringRedisTemplate.opsForHash().putAll(RedisConstants.LOGIN_USER_INFO+phone, data);



        //5.发送验证码
        log.debug("发送短信验证码成功,验证码:{}",code);
        //6.返回OK
       return Result.ok();

    }


    /**
     * 实现登录功能
     * @param loginForm
     * @param session
     * @return
     */
    @Override
    public Result login(LoginFormDTO loginForm, HttpSession session) {

        String userPhone = loginForm.getPhone();
        String userCode = loginForm.getCode();

        Map<Object, Object> entries = stringRedisTemplate
                .opsForHash()
                .entries(RedisConstants.LOGIN_USER_INFO+userPhone);

        String phone = (String) entries.get(RedisConstants.LOGIN_PHONE_KEY);
        String code = (String) entries.get(LOGIN_CODE_KEY);

        if (StrUtil.isEmpty(phone) || !phone.equals(userPhone)) {
            return Result.fail("手机号错误");
        }
        if (StrUtil.isEmpty(loginForm.getCode()) || !code.equals(userCode)) {
            return Result.fail("验证码错误");
        }


     /*
        //从Redis获取验证码和手机号校验
        String cacheCode = stringRedisTemplate.opsForValue().get(LOGIN_CODE_KEY+userPhone);
        String phoneCode = stringRedisTemplate.opsForValue().get(RedisConstants.LOGIN_PHONE_KEY+userPhone);


        //校验手机号格式
        if (RegexUtils.isPhoneInvalid(userPhone)) {
            //2.如果不符合,返回错误信息
            return Result.fail("手机号格式错误");
        }

        //校验获取验证码时的手机号(已存入Redis)与登录时输入的手机号是否一致
        if (StrUtil.isEmpty(userPhone) || !userPhone.equals(phoneCode)) {
            return Result.fail("手机号前后不一致");
        }

        //校验验证码是否正确且不为空
        //校验获取的验证码时(已存入Redis)与登录时输入的验证码是否一致
        if (cacheCode == null || !cacheCode.equals(userCode)  ) {
            //如果为空,则验证码过期,要不就是验证码没填,报错
            //如果验证码错误,则报错
            return Result.fail("验证码错误!");
        }
*/
        //如果验证码正确,则查询数据库否有此用户信息(select * from tb_user where userPhone = ?)
        User user = lambdaQuery()
                .eq(User::getPhone, userPhone).one();

        //判断用户是否存在
        if (user == null){
            //如果没有,则是新用户,进行注册操作
            user = createUserWithPhone(userPhone);
        }
        //保存用户信息到Redis中
        //随机生成token,作为登录令牌
        String token = UUID.randomUUID().toString(true);


        //防止消息泄露
        UserDTO userDTO = BeanUtil.copyProperties(user, UserDTO.class);


        //存储(putAll可以一次把所有键值对存入,用map包装)
        Map<String, Object> userMap = BeanUtil.beanToMap(userDTO,new HashMap<>(),
                CopyOptions.create()
                        .setIgnoreNullValue(true)//允许忽略空值
                        .setFieldValueEditor((fielName,fielValue) -> fielValue.toString()));

        stringRedisTemplate.opsForHash().putAll(RedisConstants.LOGIN_USER_KEY+token,userMap);
        //设置token有效期
        stringRedisTemplate.expire(RedisConstants.LOGIN_USER_KEY+token,100,TimeUnit.HOURS);
        return Result.ok(token);
    }


    /**
     * 用户签到
     * @return
     */
    @Override
    public Result sign() {
        //获取当前用户
        Long userId = UserHolder.getUser().getId();
        User user = query().eq("id", userId).one();

        //获取日期
        LocalDateTime now = LocalDateTime.now();

        //拼接key "sgin:userId:time
        String keySuffix = now.format(DateTimeFormatter.ofPattern(":yyyy:MM"));
        String key = RedisConstants.USER_SIGN_KEY+user.getId()+keySuffix;

        //获取今天是本月的第几天
        int dayOfMonth = now.getDayOfMonth();

        //写入redis setbit key offset  1
        stringRedisTemplate.opsForValue().setBit(key,dayOfMonth - 1, true);
        return Result.ok();
    }

    /**
     * 统计用户本月截止至今天的连续签到天数
     * @return
     */
    @Override
    public Result signCount() {
        //获取当前用户
        Long userId = UserHolder.getUser().getId();

        //获取日期
        LocalDateTime now = LocalDateTime.now();

        //拼接key "sgin:userId:time
        String keySuffix = now.format(DateTimeFormatter.ofPattern(":yyyy:MM"));
        String key = RedisConstants.USER_SIGN_KEY+userId+keySuffix;

        //获取今天是本月的第几天
        int dayOfMonth = now.getDayOfMonth();

        //获取本月截止今天为止的全部签到记录,返回的是一个十进制的数字
        List<Long> result = stringRedisTemplate.opsForValue().bitField(
                key,
                BitFieldSubCommands.create()//创建子命令
                        .get(BitFieldSubCommands.BitFieldType.unsigned(dayOfMonth))//设置类型 无符号
                        .valueAt(0)//起始角标
        );


        if (result == null || result.isEmpty()){
            return Result.ok(0);
        }
        Long num = result.get(0);
        //循环遍历
        int count = 0;
        while (true){
            //让这个数字与1做 与 运算,得到数字的最后一个bit位
            if ((num & 1) == 0){ //判断这个bit位是否为0
                //如果为0,说明未签到,结束
                break;
            }
            else {
                //如果不为0,说明已签到.计数器+1
                count++;
            }
            //把数字右移一位,抛弃最后一位
            num >>>= 1;
        }
        return Result.ok(count);
    }


    /**
     * 创建新用户,保存进数据库
     * @param phone
     * @return
     */
    private User createUserWithPhone(String phone) {
        //创建用户
        User user = new User();
        user.setPhone(phone);
        //生成昵称
        user.setNickName(SystemConstants.USER_NICK_NAME_PREFIX +RandomUtil.randomString(10));
        //保存用户
        save(user);
        return user;
    }
}
